using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using NLog;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FileSyncApp;

/// <summary>
/// FileSyncApp 应用程序的主窗口类
/// 提供多任务文件同步功能的用户界面，包括任务管理、路径选择、同步控制、日志显示等功能
/// </summary>
/// <remarks>
/// 此类负责：
/// - 用户界面的初始化和事件处理
/// - 多任务同步管理器的管理和控制
/// - 系统托盘功能的集成
/// - 键盘快捷键的支持
/// - 配置文件的加载和保存
/// - 实时日志显示和状态更新
/// </remarks>
public partial class MainWindow : Window
{
    /// <summary>
    /// NLog 日志记录器实例
    /// 用于记录主窗口相关的操作和错误信息
    /// </summary>
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();
    
    /// <summary>
    /// 多任务同步管理器实例
    /// 负责执行实际的多任务文件同步操作
    /// </summary>
    private MultiTaskSyncManager? syncManager;
    
    /// <summary>
    /// 配置管理器实例
    /// 负责加载和保存应用程序配置
    /// </summary>
    private ConfigManager configManager;
    
    /// <summary>
    /// 系统托盘管理器实例
    /// 负责系统托盘图标和相关功能
    /// </summary>
    private TrayManager trayManager;
    
    /// <summary>
    /// 键盘快捷键管理器实例
    /// 负责处理全局键盘快捷键
    /// </summary>
    private KeyboardShortcuts keyboardShortcuts;
    
    /// <summary>
    /// 任务列表的可观察集合
    /// 用于绑定到UI的任务列表控件
    /// </summary>
    private ObservableCollection<SyncTask> tasks = new ObservableCollection<SyncTask>();
    
    #region UI 控件字段
    /// <summary>任务名称输入框</summary>
    private TextBox? taskNameTextBox;
    /// <summary>源文件夹路径输入框</summary>
    private TextBox? sourcePathTextBox;
    /// <summary>目标文件夹路径输入框</summary>
    private TextBox? targetPathTextBox;
    /// <summary>优先级选择下拉框</summary>
    private ComboBox? priorityComboBox;
    /// <summary>浏览源文件夹按钮</summary>
    private Button? browseSourceButton;
    /// <summary>浏览目标文件夹按钮</summary>
    private Button? browseTargetButton;
    /// <summary>添加任务按钮</summary>
    private Button? addTaskButton;
    /// <summary>启动所有任务按钮</summary>
    private Button? startAllTasksButton;
    /// <summary>停止所有任务按钮</summary>
    private Button? stopAllTasksButton;
    /// <summary>保存配置按钮</summary>
    private Button? saveConfigButton;
    /// <summary>任务列表控件</summary>
    private ListBox? taskListBox;
    /// <summary>日志显示文本框</summary>
    private TextBox? logTextBox;
    /// <summary>状态显示文本块</summary>
    private TextBlock? statusTextBlock;
    /// <summary>任务数量显示文本块</summary>
    private TextBlock? taskCountTextBlock;
    /// <summary>运行中任务数量显示文本块</summary>
    private TextBlock? runningTaskCountTextBlock;
    /// <summary>文件数量显示文本块</summary>
    private TextBlock? fileCountTextBlock;
    #endregion

    /// <summary>
    /// 初始化 MainWindow 类的新实例
    /// </summary>
    /// <remarks>
    /// 构造函数执行以下初始化操作：
    /// 1. 初始化 Avalonia UI 组件
    /// 2. 创建配置管理器实例
    /// 3. 初始化系统托盘管理器
    /// 4. 初始化键盘快捷键管理器
    /// 5. 初始化用户界面控件
    /// 6. 加载保存的配置
    /// 7. 设置窗口加载时自动最小化到托盘
    /// </remarks>
        public MainWindow()
        {
            InitializeComponent();
            configManager = new ConfigManager();
            
            // 初始化托盘管理器
            trayManager = new TrayManager(this);
            
            // 初始化键盘快捷键
            keyboardShortcuts = new KeyboardShortcuts(this, trayManager);
            
            InitializeUI();
            LoadConfiguration();
            
            // 根据配置决定是否在加载时最小化到托盘
            this.Loaded += (sender, e) =>
            {
                var config = configManager.LoadConfig();
                if (config.StartMinimized)
                {
                    trayManager?.MinimizeToTray();
                    trayManager?.ShowTrayNotification("多任务文件同步工具已启动并在后台运行");
                }
            };
        }

    /// <summary>
    /// 初始化用户界面控件
    /// 查找XAML中定义的控件并绑定事件处理程序
    /// </summary>
    private void InitializeUI()
    {
        // 查找UI控件
        taskNameTextBox = this.FindControl<TextBox>("TaskNameTextBox");
        sourcePathTextBox = this.FindControl<TextBox>("SourcePathTextBox");
        targetPathTextBox = this.FindControl<TextBox>("TargetPathTextBox");
        priorityComboBox = this.FindControl<ComboBox>("PriorityComboBox");
        browseSourceButton = this.FindControl<Button>("BrowseSourceButton");
        browseTargetButton = this.FindControl<Button>("BrowseTargetButton");
        addTaskButton = this.FindControl<Button>("AddTaskButton");
        startAllTasksButton = this.FindControl<Button>("StartAllTasksButton");
        stopAllTasksButton = this.FindControl<Button>("StopAllTasksButton");
        saveConfigButton = this.FindControl<Button>("SaveConfigButton");
        taskListBox = this.FindControl<ListBox>("TaskListBox");
        logTextBox = this.FindControl<TextBox>("LogTextBox");
        statusTextBlock = this.FindControl<TextBlock>("StatusTextBlock");
        taskCountTextBlock = this.FindControl<TextBlock>("TaskCountTextBlock");
        runningTaskCountTextBlock = this.FindControl<TextBlock>("RunningTaskCountTextBlock");
        fileCountTextBlock = this.FindControl<TextBlock>("FileCountTextBlock");

        // 绑定事件处理程序
        if (browseSourceButton != null)
            browseSourceButton.Click += BrowseSourceButton_Click;
        if (browseTargetButton != null)
            browseTargetButton.Click += BrowseTargetButton_Click;
        // addTaskButton 事件已在XAML中绑定，无需重复绑定
        if (startAllTasksButton != null)
            startAllTasksButton.Click += StartAllTasksButton_Click;
        if (stopAllTasksButton != null)
            stopAllTasksButton.Click += StopAllTasksButton_Click;
        if (saveConfigButton != null)
            saveConfigButton.Click += SaveConfigButton_Click;

        // 设置任务列表数据绑定
        if (taskListBox != null)
            taskListBox.ItemsSource = tasks;

        // 初始化多任务同步管理器
        syncManager = new MultiTaskSyncManager();
        syncManager.LogMessage += OnLogMessage;
        syncManager.TaskStatusChanged += OnTaskStatusChanged;
        syncManager.Start();
    }

    /// <summary>
    /// 加载应用程序配置
    /// </summary>
    private void LoadConfiguration()
    {
        try
        {
            var config = configManager.LoadConfig();
            
            if (sourcePathTextBox != null)
                sourcePathTextBox.Text = config.SourcePath;
            if (targetPathTextBox != null)
                targetPathTextBox.Text = config.TargetPath;
            
            AppendLog("配置加载完成");
            logger.Info("配置加载完成");
        }
        catch (Exception ex)
        {
            AppendLog($"加载配置失败: {ex.Message}");
            logger.Error(ex, "加载配置失败");
        }
    }

    private async void BrowseSourceButton_Click(object? sender, RoutedEventArgs e)
    {
        await BrowseFolder(sourcePathTextBox, "选择源文件夹");
    }

    private async void BrowseTargetButton_Click(object? sender, RoutedEventArgs e)
    {
        await BrowseFolder(targetPathTextBox, "选择目标文件夹");
    }

    private async Task BrowseFolder(TextBox? textBox, string title)
    {
        if (textBox == null) return;

        var topLevel = TopLevel.GetTopLevel(this);
        if (topLevel == null) return;

        var folders = await topLevel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
        {
            Title = title,
            AllowMultiple = false
        });

        if (folders.Count > 0)
        {
            textBox.Text = folders[0].Path.LocalPath;
        }
    }

    private void AddTaskButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            var taskName = taskNameTextBox?.Text ?? "新同步任务";
            var sourcePath = sourcePathTextBox?.Text ?? "";
            var targetPath = targetPathTextBox?.Text ?? "";
            var priorityItem = priorityComboBox?.SelectedItem as ComboBoxItem;
            var priority = Enum.Parse<SyncTaskPriority>(priorityItem?.Tag?.ToString() ?? "Normal");

            if (string.IsNullOrWhiteSpace(sourcePath) || string.IsNullOrWhiteSpace(targetPath))
            {
                AppendLog("错误: 请选择源文件夹和目标文件夹");
                return;
            }

            if (!Directory.Exists(sourcePath))
            {
                AppendLog($"错误: 源文件夹不存在: {sourcePath}");
                return;
            }

            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
                AppendLog($"创建目标文件夹: {targetPath}");
            }

            var task = new SyncTask(taskName, sourcePath, targetPath, priority);

            syncManager?.AddTask(task);
            tasks.Add(task);
            
            AppendLog($"添加任务: {taskName}");
            UpdateStatusBar();
        }
        catch (Exception ex)
        {
            AppendLog($"添加任务失败: {ex.Message}");
            logger.Error(ex, "添加任务失败");
        }
    }

    private void StartAllTasksButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            foreach (var task in tasks.Where(t => t.Status == SyncTaskStatus.Pending || t.Status == SyncTaskStatus.Stopped))
            {
                syncManager?.StartTask(task.Id);
            }
            AppendLog("启动所有任务");
            UpdateStatusBar();
        }
        catch (Exception ex)
        {
            AppendLog($"启动任务失败: {ex.Message}");
            logger.Error(ex, "启动任务失败");
        }
    }

    private async void StopAllTasksButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            foreach (var task in tasks.Where(t => t.Status == SyncTaskStatus.Running))
            {
                await syncManager?.StopTaskAsync(task.Id);
            }
            AppendLog("停止所有任务");
            UpdateStatusBar();
        }
        catch (Exception ex)
        {
            AppendLog($"停止任务失败: {ex.Message}");
            logger.Error(ex, "停止任务失败");
        }
    }

    private void SaveConfigButton_Click(object? sender, RoutedEventArgs e)
    {
        try
        {
            var config = new SyncConfig
            {
                SourcePath = sourcePathTextBox?.Text ?? "",
                TargetPath = targetPathTextBox?.Text ?? "",
                AutoStart = false,
                StartMinimized = false
            };

            configManager.SaveConfig(config);
            AppendLog("配置保存成功");
        }
        catch (Exception ex)
        {
            AppendLog($"保存配置失败: {ex.Message}");
            logger.Error(ex, "保存配置失败");
        }
    }

    // 任务相关的事件处理方法
    public void OnAddTaskClick(object? sender, RoutedEventArgs e)
    {
        AddTaskButton_Click(sender, e);
    }

    public void OnStartAllTasksClick(object? sender, RoutedEventArgs e)
    {
        StartAllTasksButton_Click(sender, e);
    }

    public void OnStopAllTasksClick(object? sender, RoutedEventArgs e)
    {
        StopAllTasksButton_Click(sender, e);
    }

    public void OnSaveConfigClick(object? sender, RoutedEventArgs e)
    {
        SaveConfigButton_Click(sender, e);
    }

    public void OnStartTaskClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag is string taskId)
        {
            try
            {
                syncManager?.StartTask(taskId);
                AppendLog($"启动任务: {taskId}");
                UpdateStatusBar();
            }
            catch (Exception ex)
            {
                AppendLog($"启动任务失败: {ex.Message}");
                logger.Error(ex, "启动任务失败");
            }
        }
    }

    public async void OnStopTaskClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag is string taskId)
        {
            try
            {
                await syncManager?.StopTaskAsync(taskId);
                AppendLog($"停止任务: {taskId}");
                UpdateStatusBar();
            }
            catch (Exception ex)
            {
                AppendLog($"停止任务失败: {ex.Message}");
                logger.Error(ex, "停止任务失败");
            }
        }
    }

    public async void OnRemoveTaskClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag is string taskId)
        {
            try
            {
                await syncManager?.RemoveTaskAsync(taskId);
                var task = tasks.FirstOrDefault(t => t.Id == taskId);
                if (task != null)
                {
                    tasks.Remove(task);
                }
                AppendLog($"删除任务: {taskId}");
                UpdateStatusBar();
            }
            catch (Exception ex)
            {
                AppendLog($"删除任务失败: {ex.Message}");
                logger.Error(ex, "删除任务失败");
            }
        }
    }

    public void OnTaskSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        // 任务选择变化处理
    }

    // 多任务同步管理器事件处理
    private void OnLogMessage(string message)
    {
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            AppendLog(message);
        });
    }

    private void OnTaskStatusChanged(SyncTask task)
    {
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            var existingTask = tasks.FirstOrDefault(t => t.Id == task.Id);
            if (existingTask != null)
            {
                existingTask.Status = task.Status;
                UpdateStatusBar();
            }
        });
    }

    private void UpdateStatusBar()
    {
        if (statusTextBlock != null)
        {
            var runningCount = tasks.Count(t => t.Status == SyncTaskStatus.Running);
            statusTextBlock.Text = runningCount > 0 ? "同步进行中..." : "多任务同步管理器就绪";
        }

        if (taskCountTextBlock != null)
        {
            taskCountTextBlock.Text = $"任务数: {tasks.Count}";
        }

        if (runningTaskCountTextBlock != null)
        {
            var runningCount = tasks.Count(t => t.Status == SyncTaskStatus.Running);
            runningTaskCountTextBlock.Text = $"运行中: {runningCount}";
        }
    }

    private void AppendLog(string message)
    {
        if (logTextBox != null)
        {
            var timestamp = DateTime.Now.ToString("HH:mm:ss");
            var logMessage = $"[{timestamp}] {message}\n";
            logTextBox.Text += logMessage;
            
            // 自动滚动到底部
            if (logTextBox.Parent is ScrollViewer scrollViewer)
            {
                scrollViewer.ScrollToEnd();
            }
        }
    }

    private void OnShowWindowClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        trayManager?.ShowMainWindow();
    }

    private void OnHideWindowClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        trayManager?.HideMainWindow();
    }

    private void OnExitAppClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        trayManager?.ExitApplication();
    }

    private async void OnCopyLogClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        try
        {
            if (logTextBox != null && !string.IsNullOrEmpty(logTextBox.Text))
            {
                var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
                if (clipboard != null)
                {
                    await clipboard.SetTextAsync(logTextBox.Text);
                    AppendLog("日志已复制到剪贴板");
                    logger.Info("日志已复制到剪贴板");
                }
            }
            else
            {
                AppendLog("没有日志内容可复制");
            }
        }
        catch (Exception ex)
        {
            AppendLog($"复制日志失败: {ex.Message}");
            logger.Error(ex, "复制日志失败");
        }
    }

    public void OnClearLogClick(object? sender, RoutedEventArgs e)
    {
        if (logTextBox != null)
        {
            logTextBox.Text = "";
            AppendLog("日志已清空");
        }
    }

    protected override async void OnClosed(EventArgs e)
    {
        // 停止同步管理器
        if (syncManager != null)
        {
            await syncManager.StopAsync();
        }
        
        // 释放托盘管理器
        trayManager?.Dispose();
        
        // 释放键盘快捷键管理器
        keyboardShortcuts?.Dispose();
        
        base.OnClosed(e);
    }
}